package com.xkspringmvc.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xkspringmvc.model.User;
import com.xkspringmvc.service.UserService;
import com.xkspringmvc.utils.EncryptUtil;

@Controller
@RequestMapping("/user")
public class UserController {
	private static Logger log = LoggerFactory.getLogger(UserController.class);
	private final static int DEFAULT_PAGE = 1;
	private final static int DEFAULT_ROWS = 10;

	@Autowired
	private UserService userService;

	/**
	 * 显示所有用户列表
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String getUserList(HttpServletRequest request, Model model,
			@RequestParam(required = false, defaultValue = "1") int page,
			@RequestParam(required = false, defaultValue = "10") int rows) {
		PageHelper.startPage(page > 0 ? page : DEFAULT_PAGE,
				rows > 0 ? rows : DEFAULT_ROWS);
		List<User> userList = userService.getUserList();
		PageInfo<User> pageInfo = new PageInfo<>(userList);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("page", page);
		model.addAttribute("rows", rows);
		for (User user : userList) {
			log.info(user.toString());
		}
		User loginUser = userService.selectByUsername((String) request.getSession().getAttribute("username"));
		model.addAttribute("loginUser", loginUser);
		return "index";
	}

	/**
	 * 到编辑用户页面
	 * 
	 * @param request
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/editUser")
	public String editUser(HttpServletRequest request, Model model, Long id) {
		User user = null;
		if (id != null) {
			user = userService.selectByPrimaryKey(id);
		}
		model.addAttribute("user", user);
		return "editUser";
	}

	/**
	 * 新增或修改用户
	 * 
	 * @param request
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping("/addOrUpdateUser")
	public String addUser(HttpServletRequest request, Model model, User user) {
		User userTar = null;

		if (user != null) {
			if (user.getId() != null) {
				userTar = userService.selectByPrimaryKey(user.getId());
			}
			if (userTar != null) {
				userService.updateByPrimaryKeySelective(user);
				log.info("updateUser success");
			} else {
				// 新增用户默认密码为12345678,需要及时修改
				user.setPassword(EncryptUtil.md5("12345678"));
				userService.insert(user);
				log.info("addUser success");
			}
		}

		User loginUser = userService.selectByUsername((String) request.getSession().getAttribute("username"));
		model.addAttribute("loginUser", loginUser);
		return "index";
	}

	/**
	 * 删除用户
	 * 
	 * @param request
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteUser")
	public String deleteUser(HttpServletRequest request, Model model, Long id) {
		if (id != null) {
			userService.deleteByPrimaryKey(id);
			log.info("deleteUser success");
		}
		User loginUser = userService.selectByUsername((String) request.getSession().getAttribute("username"));
		model.addAttribute("loginUser", loginUser);
		return "index";
	}
	
	/**
	 * 跳到登录页面
	 * @param request
	 * @param model
	 * @return
	 */	
	@RequestMapping("/toLogin")
	public String toLogin(HttpServletRequest request, Model model) {
		return "login";
	}
	
	/**
	 * 登录
	 * @param request
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request, Model model, User user) {
		if (user == null || StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			model.addAttribute("error_msg", "参数不能为空！");
			return "login";
		}

		User existUser = userService.selectByUsername(user.getUsername());
		if (existUser == null) {
			model.addAttribute("error_msg", "用户名不存在或密码错误！");
			return "login";
		}

		if (!existUser.getPassword().equals(EncryptUtil.md5(user.getPassword()))) {
			model.addAttribute("error_msg", "用户名不存在或密码错误！");
			return "login";
		}
		log.info("login success");
		// 设置登录状态到session中
		request.getSession().setAttribute("username", user.getUsername());
		model.addAttribute("error_msg", "");
		User loginUser = userService.selectByUsername((String) request.getSession().getAttribute("username"));
		model.addAttribute("loginUser", loginUser);
		return "index";
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, Model model) {
		request.getSession().removeAttribute("username");
		request.getSession().invalidate();
		return "login";
	}

	/**
	 * 跳到注册页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/toRegister")
	public String toRegister(HttpServletRequest request, Model model) {
		return "register";
	}
	
	/**
	 * 注册
	 * @param request
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping("/register")
	public String register(HttpServletRequest request, Model model, User user) {
		if (user == null || StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getUsername())
				|| StringUtils.isBlank(user.getPassword()) || StringUtils.isBlank(user.getRePassword())) {
			model.addAttribute("error_msg", "参数不能为空！");
			return "register";
		}

		if (!user.getPassword().equals((user.getRePassword()))) {
			model.addAttribute("error_msg", "二次输入密码不一致！");
			return "register";
		}

		User existUser = userService.selectByUsername(user.getUsername());
		if (existUser != null) {
			model.addAttribute("error_msg", "用户名已经存在！");
			return "register";
		}

		user.setPassword(EncryptUtil.md5(user.getPassword()));
		userService.insert(user);
		log.info("register success");
		model.addAttribute("error_msg", "");
		return "login";
	}
	
	/**
	 * 跳转到修改密码页面
	 * @param request
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/toUpdatePassword")
	public String toUpdatePassword(HttpServletRequest request, Model model, Long id) {
		User userTar = null;
		if (id != null) {
			userTar = userService.selectByPrimaryKey(id);
		}
		if (userTar != null) {
			model.addAttribute("user", userTar);
			return "updatePassword";
		}

		User loginUser = userService.selectByUsername((String) request.getSession().getAttribute("username"));
		model.addAttribute("loginUser", loginUser);
		return "index";
	}
	
	/**
	 * 修改密码  
	 * @param request
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping("/updatePassword")
	public String updatePassword(HttpServletRequest request, Model model, User user) {
		User userTar = null;
		if(user == null || user.getId() == null){
			model.addAttribute("error_msg", "参数不能为空！");
			return "updatePassword";
		}
		
		userTar = userService.selectByPrimaryKey(user.getId());
		if (userTar == null) {
			model.addAttribute("error_msg", "用户不存在！");
			return "updatePassword";
		}
		
		if(!userTar.getPassword().equals(EncryptUtil.md5(user.getPassword()))){
			model.addAttribute("error_msg", "原密码不正确！");
			return "updatePassword";
		}
		
		userTar.setPassword(EncryptUtil.md5(user.getRePassword()));
		userService.updateByPrimaryKeySelective(userTar);
		
		log.info("updatePassword success");
		User loginUser = userService.selectByUsername((String) request.getSession().getAttribute("username"));
		model.addAttribute("loginUser", loginUser);
		return "index";
	}
}
